package durst.data.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.stmt.PreparedDelete;
import com.j256.ormlite.stmt.PreparedUpdate;
import com.j256.ormlite.stmt.Where;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.DatabaseTableConfig;

import durst.data.Account;
import durst.data.UserCalendar;

public class UserCalendarDao<T, ID> extends BaseDaoImpl<T, ID> {
	public UserCalendarDao(ConnectionSource source, DatabaseTableConfig<T> tableConfig)
			throws SQLException {
		super(source, tableConfig);
	}

	@SuppressWarnings("unchecked")
	public UserCalendarDao(ConnectionSource connectionSource) throws SQLException {
		super(connectionSource, (Class<T>) UserCalendar.class);
	}

	public List<T> getCalendarsForAccountId(Account acc, boolean jumplistOnly) throws SQLException {
		Where<T, ID> where = queryBuilder().where().eq(UserCalendar.OWNER_ID, acc.getId());
		if (jumplistOnly)
			where.and(
					where,
					where.or(where.eq(UserCalendar.JUMPLIST, true),
							where.eq(UserCalendar.DEF, true)));
		return query(where.prepare());
	}

	public T getDefaultCalendarForAccount(Account acc) throws SQLException {
		List<T> res = query(queryBuilder().where().eq(UserCalendar.OWNER_ID, acc.getId()).and()
				.eq(UserCalendar.DEF, 1).prepare());

		assert (res.size() <= 1);

		return res.size() == 1 ? res.get(0) : null;
	}

	@SuppressWarnings("unchecked")
	public void jumplist(Account acc, List<UserCalendar> cals, boolean jump) throws SQLException {
		List<Integer> ids = new ArrayList<Integer>(cals.size());
		for (UserCalendar cal : cals)
			ids.add(cal.getId());
		update((PreparedUpdate<T>) updateBuilder().updateColumnValue(UserCalendar.JUMPLIST, jump)
				.where().eq(UserCalendar.OWNER_ID, acc.getId()).and().in(UserCalendar.ID, ids)
				.prepare());
	}

	@SuppressWarnings("unchecked")
	public void deleteCalendars(Account acc, List<UserCalendar> cals) throws SQLException {
		List<Integer> ids = new ArrayList<Integer>(cals.size());
		for (UserCalendar cal : cals)
			ids.add(cal.getId());
		delete((PreparedDelete<T>) deleteBuilder().where().eq(UserCalendar.OWNER_ID, acc.getId())
				.and().eq(UserCalendar.DEF, false).and().in(UserCalendar.ID, ids).prepare());
	}
}
